<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 头像区域 -->
      <div class="avatar_box">
        <img src="../assets/logo.png" alt />
      </div>
      <!-- 登录表单区域 -->
      <el-form label-width="0px" :model="userForm" :rules="userFormRule" ref="userFormRef" class="login_form">
        <!-- 用户名 -->
        <el-form-item  prop="username">
          <el-input prefix-icon="iconfont icon-user" v-model="userForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item  prop="password">
          <el-input prefix-icon="iconfont icon-3702mima" v-model="userForm.password" type="password"></el-input>
        </el-form-item>
        <!-- 按钮区域 -->
        <el-form-item class="btns">
          <el-button type="info" @click="reset">重置</el-button>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      userForm: {
        username: 'admin',
        password: '123456'
      },
      userFormRule: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    reset () {
      this.$refs.userFormRef.resetFields()
    },
    login () {
      this.$refs.userFormRef.validate(async valid => {
        // 前端验证失败
        if (!valid) return false
        // 解构的写法 将该集合中data属性值赋予变量res上
        const { data: res } = await this.$http.post('login', this.userForm)
        // 当前返回值是一个promise 则可以添加关键字await进行优化,但是必须前边用async修饰是一个异步的方法
        if (res.meta.status !== 200) return this.$message.error('验证账号或密码错误!')
        this.$message.success('登录成功!')
        // 将数据集中的token信息保存到 sessionStorage中
        window.sessionStorage.setItem('token', res.data.token)
        // 跳转
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login_container {
  height: 100%;
  background-color: rgb(135, 43, 197);
}

.login_box {
  width: 450px;
  height: 300px;
  background-color: rgb(255, 255, 255);
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.avatar_box {
  height: 130px;
  width: 130px;
  border: 1px solid #eee;
  border-radius: 50%;
  padding: 10px;
  box-shadow: 0 0 10px #ddd;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgb(255, 255, 255);

  img {
    height: 100%;
    width: 100%;
    border-radius: 50%;
    background-color: #eee;
  }
}

.btns {
  display: flex; //变成弹性盒模型
  justify-content: flex-end;
}

.login_form {
  width: 100%;
  padding: 0 20px;
  position: absolute;
  box-sizing: border-box;
  bottom: 0px;
}
</style>
